﻿<template>
    <div class="DepartmentDetail">
        <MyDialog :model-value="true" :type="DialogType.C1" :title="title" @close="onClose">
            <el-form ref="DepartmentDetailFormRef" label-width="80" :model="thisData" :rules="rules">
                <el-form-item label="上级部门" v-if="thisData.type != Enums.Department_Type.集团" prop="parentID">
                    <el-input v-model="thisData.parentName" maxlength="50" v-if="thisData.type != Enums.Department_Type.普通 || Gx.IsEmpty(rowAutoID)" disabled></el-input>
                    <DepartmentIds ref="ParentDepartmentRef" v-else v-model="thisData.parentID" :isLoadingData="false" :multiple="false" @change="onParentDepartmentChange"></DepartmentIds>
                </el-form-item>

                <el-form-item label="名称" prop="name">
                    <el-input v-model="thisData.name" maxlength="50"></el-input>
                </el-form-item>

                <el-form-item label="负责人" prop="leaderName">
                    <el-input v-model="thisData.leaderName" maxlength="50" disabled>
                        <template #append>
                            <el-button @click="onShowSelectLeader">选择</el-button>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="thisData.type" @change="onRadioChange">
                        <el-radio v-for="item in departmentTypeArr" :label="item.value">{{ item.text }}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="省" prop="provinceID" v-if="thisData.type == Enums.Department_Type.矿山">
                    <DataSelect ref="ProvinceRef" class="w-100" table="Province" action="GetSearch" v-model:id="thisData.provinceID" @change="onProvinceChange"></DataSelect>
                </el-form-item>

                <el-form-item label="市" prop="cityID" v-if="thisData.type == Enums.Department_Type.矿山">
                    <DataSelect ref="CityRef" class="w-100" table="City" action="GetSearch" v-model:id="thisData.cityID" :isLoadingData="false" :filter="CityFilter" @change="onCityChange"></DataSelect>
                </el-form-item>

                <el-form-item label="区/县" prop="areaID" v-if="thisData.type == Enums.Department_Type.矿山">
                    <DataSelect ref="AreaRef" class="w-100" table="Area" action="GetSearch" v-model:id="thisData.areaID" :filter="AreaFilter" :isLoadingData="false"></DataSelect>
                </el-form-item>

                <el-form-item label="数据归属" prop="selectDepartmentIDs">
                    <DepartmentIds v-model="thisData.selectDepartmentIDs"></DepartmentIds>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button type="primary" :loading="loading" @click="onSave">保存</el-button>
            </template>
        </MyDialog>

        <UserSelect ref="UserSelectRef" v-if="isShowSelectLeader" @close="onCloseSelectLeader" :hasCheckbox="false" :hasRadio="true"></UserSelect>
    </div>
</template>

<script lang="ts" setup>
import Enums from "@/gx/Enums";
import Gx from "@/gx/Gx";
import { FormRules } from "element-plus";
import { DialogType } from "@/_gx/TsEnums";
import UserSelect from "../User/UserSelect.vue";
import _ from "lodash";

//处理枚举
let departmentTypeArr = ref([]);

//接收父组件的传值
const rowAutoID = inject("rowAutoID") as Ref<number | null>;

//定义当前页面数据对象
const thisData = ref<any>({
    selectDepartmentIDs: [-1],
});

//loading...
const loading = ref(false);

//拍平的部门数据
const allDepartmentList = ref([]);

//定义表单验证规则
const rules = ref<FormRules>({
    parentID: [{ required: true, message: "请选择上级部门", trigger: "blur" }],
    // leaderName: [{ required: true, message: "请输入负责人", trigger: "blur" }],
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    type: [{ required: true, message: "请选择类型", trigger: "change" }],
    provinceID: [{ required: true, message: "请选择省", trigger: "blur" }],
    cityID: [{ required: true, message: "请选择市", trigger: "blur" }],
    areaID: [{ required: true, message: "请选择县", trigger: "blur" }],
    selectDepartmentIDs: [{ required: true, message: "请选择数据归属", trigger: "blur" }],
});

//标题
const title = computed(() => {
    if (Gx.IsEmpty(rowAutoID.value)) {
        return "部门详情 - 创建";
    } else {
        return `部门详情 - 编辑 - ${thisData.value.name}`;
    }
});

//定义市、县所需要的对象
const ProvinceRef = ref(null);
const CityRef = ref(null);
const CityFilter = ref({ _ProvinceID: null });
const AreaRef = ref(null);
const AreaFilter = ref({ _CityID: null });
const ParentDepartmentRef = ref(null);

//初始化
const Init = async (parentID, parentName, parentType) => {
    thisData.value.parentID = parentID;
    thisData.value.parentName = parentName;
    thisData.value.parentType = parentType;

    let _arr = Enums.Department_Type.ToArray();
    departmentTypeArr.value = _arr;

    await App.CallApi(Api.Department.GetAll(), {
        success: (res) => {
            allDepartmentList.value = res;
        },
    });

    //对于添加时，类型的处理
    if (Gx.IsEmpty(rowAutoID.value)) {
        _arr.splice(0, 1);

        if (thisData.value.parentType == Enums.Department_Type.集团) {
            thisData.value.type = Enums.Department_Type.矿山;
        } else {
            _arr.splice(0, 1);
            thisData.value.type = Enums.Department_Type.普通;
        }

        departmentTypeArr.value = _arr;
    }

    //对于修改时，类型的处理、地域选择的处理
    if (!Gx.IsEmpty(rowAutoID.value)) {
        let _res: any = {};
        await App.CallApi(Api.Department.GetByID(rowAutoID.value), {
            success: (res) => {
                _res = res;
            },
        });

        if (_res.type == Enums.Department_Type.集团) {
            _arr = [_arr[0]];
        } else if (_res.type == Enums.Department_Type.矿山) {
            _arr.splice(0, 1);
        } else if (_res.type == Enums.Department_Type.普通 && _res.parentType == Enums.Department_Type.集团) {
            _arr.splice(0, 1);
        } else {
            _arr.splice(0, 1);
            _arr.splice(0, 1);
        }

        departmentTypeArr.value = Gx.DeepCopy(_arr);
        thisData.value = _res;

        if (thisData.value.type == Enums.Department_Type.矿山) {
            nextTick(() => {
                CityFilter.value._ProvinceID = thisData.value.provinceID;
                CityRef.value.GetList();

                AreaFilter.value._CityID = thisData.value.cityID;
                AreaRef.value.GetList();
            });
        }
    }
};

//监听部门类型的变化
watch(
    () => thisData.value.type,
    (newVal, oldVal) => {
        if (newVal == Enums.Department_Type.普通 && !Gx.IsEmpty(rowAutoID.value)) {
            SetParentDepartmentData();
        }
    }
);

//获取上级部门数据
const SetParentDepartmentData = () => {
    let list = Gx.DeepCopy(allDepartmentList.value);
    _.remove(list, (x: any) => {
        return x.departmentID == thisData.value.departmentID;
    });
    let tree = Gx.List2Tree(list, "autoID");
    nextTick(() => {
        ParentDepartmentRef.value.SetData([tree[0]]);
    });
};

//省改变
const onProvinceChange = () => {
    CityRef.value.ClearData();
    CityRef.value.ClearList();
    onCityChange();
    if (!Gx.IsEmpty(thisData.value.provinceID)) {
        CityFilter.value._ProvinceID = thisData.value.provinceID;
        CityRef.value.GetList();
    }
};

//市改变
const onCityChange = () => {
    AreaRef.value.ClearData();
    AreaRef.value.ClearList();
    if (!Gx.IsEmpty(thisData.value.cityID)) {
        AreaFilter.value._CityID = thisData.value.cityID;
        AreaRef.value.GetList();
    }
};

//类型改变
const onRadioChange = () => {
    if (thisData.value.type == Enums.Department_Type.矿山) {
        ProvinceRef.value.ClearData();
        CityRef.value.ClearData();
        CityRef.value.ClearList();
        AreaRef.value.ClearData();
        AreaRef.value.ClearList();
    }
};

//改变上级部门后，可能会导致类型的改变
const onParentDepartmentChange = () => {
    //说明：这里在界面中的parentID，其实就是上级部门的DepartmentID
    var departmentID = thisData.value.parentID;

    //在所有部门里找出当前选择的这个部门信息
    var findItem = allDepartmentList.value.find((x) => {
        return x.departmentID == departmentID;
    });

    if (!Gx.IsEmpty(findItem)) {
        let _arr = Enums.Department_Type.ToArray();
        _arr.splice(0, 1);

        //如果当前找到的这个部门不是根节点（即集团），则只有普通类型
        if (findItem.parentID != 0) {
            _arr.splice(0, 1);
        }

        departmentTypeArr.value = _arr;
        thisData.value.parentName = findItem.name;
    }
};

//表单Ref对象
const DepartmentDetailFormRef = ref(null);

//保存
const onSave = () => {
    DepartmentDetailFormRef.value.validate((isOk: boolean) => {
        if (!isOk) {
            return;
        }

        let _api = null;
        let _data = thisData.value;
        if (Gx.IsEmpty(rowAutoID.value)) {
            //添加
            _api = Api.Department.Insert;
        } else {
            //修改
            _api = Api.Department.Update;
        }

        if (_data.type == Enums.Department_Type.普通) {
            _data.provinceID = null;
            _data.cityID = null;
            _data.areaID = null;
        }

        loading.value = true;
        App.CallApi(_api, {
            data: _data,
            success: (res) => {
                emits("close", true);
            },
            complete: () => {
                loading.value = false;
            },
        });
    });
};

//关闭
const onClose = () => {
    emits("close", false);
};

/********************************************** 负责人相关 **********************************************/

//是否显示选择负责人对话框
const isShowSelectLeader = ref(false);
//负责人选择对话框Ref
const UserSelectRef = ref(null);

//显示选择负责人
const onShowSelectLeader = () => {
    isShowSelectLeader.value = true;
    nextTick(() => {
        //在这里处理负责人的回显选中
        UserSelectRef.value.SetSelectUserID(thisData.value.leaderID);
    });
};

//关闭选择负责人
const onCloseSelectLeader = (selectData) => {
    isShowSelectLeader.value = false;
    if (!Gx.IsEmpty(selectData)) {
        thisData.value.leaderID = selectData.userID;
        thisData.value.leaderName = selectData.name;
    }
};

//向上抛出的事件与方法
const emits = defineEmits(["close"]);
defineExpose({ Init });
</script>
